#pragma once
#include "Socket.hpp"

using ioservice_t = std::function<void(std::shared_ptr<Socket>& sock,InetAddr& inet)>;

class TcpServer
{
public:
    TcpServer(uint16_t port):_port(port),_listensockptr(std::make_unique<TcpSocket>()),_isruning(false)
    {
        _listensockptr->BuildTcpConnectionMethod(_port);
    }
    void Start(ioservice_t callback)
    {
        _isruning = true;
        while(_isruning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);
            if (sock == nullptr)
            {
                //LOG(LogLevel::DEBUG) << "accept fail ..." << client.StringAddr();
                continue;
            }
            std::cout << "hello" << std::endl;
            LOG(LogLevel::DEBUG) << "accept success ..." << client.StringAddr();
            pid_t id = 0;
            id = fork();
            if(id > 0)
            {
                //父进程
                sock->Close();
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;
            }
            else if(id == 0)
            {
                //子进程创建子进程
                _listensockptr->Close();
                if(fork() > 0)
                {
                    exit(OK);
                }
                callback(sock,client);
                sock->Close();
                exit(OK);
            }
            else
            {
                LOG(LogLevel::FATAL) << "fork error ...";
                // excepter(sock); // 
                exit(FORK_ERR);
            }
            
        }
        _isruning = false;
    }
    ~TcpServer()
    {}
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isruning;
};